package com.whmskj.xjlhsc.mobie.energymanage.controller;

import com.github.pagehelper.PageHelper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhsc.mobie.energymanage.service.MobileDashboardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import cn.dev33.satoken.annotation.SaIgnore;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Api(tags = "移动端-电表看板")
@RestController("mobileDashboardController")
@RequestMapping("/mobile/dashboard")
public class MobileDashboardController {
	
	@Resource
	private MobileDashboardService dashboardService;
	

	/**
	 * 获取全局能耗汇总
	 * @param day 查询日期
	 * @param process 工序筛选
	 * @return 全局能耗汇总
	 */
	@ApiOperation("获取全局能耗汇总")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "day", value = "查询日期，格式：yyyy-MM-dd", required = false, paramType = "query"),
			@ApiImplicitParam(name = "process", value = "工序筛选", required = false, paramType = "query"),
			@ApiImplicitParam(name = "collectFlag", value = "采集状态：1=采集正常，0=采集中断", required = false, paramType = "query")
	})
	@SaIgnore
	@GetMapping("/summary")
	public AjaxResult getGlobalEnergySummary(
			@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day,
			@RequestParam(required = false) String process,
            @RequestParam(required = false) Integer collectFlag) {
		return AjaxResult.success(dashboardService.getGlobalEnergySummary(day, process,collectFlag));
	}

    /**
     * 获取设备能耗列表（分页）
     * @param day 查询日期
     * @param process 工序筛选
     * @param keyword 关键字搜索
     * @return 分页设备列表
     */
    @ApiOperation(value = "获取设备能耗列表（分页）", notes = "支持 URL 或 JSON Body 传参；分页参数 pageNum/pageSize 走 URL 查询参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "day", value = "查询日期，格式：yyyy-MM-dd", required = false, paramType = "query"),
            @ApiImplicitParam(name = "process", value = "工序筛选", required = false, paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键字搜索", required = false, paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码(默认1)", required = false, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量(默认10)", required = false, paramType = "query"),
            @ApiImplicitParam(name = "collectFlag", value = "采集状态标记：1=采集正常，0=采集中断", required = false, paramType = "query"),
            @ApiImplicitParam(name = "body", value = "可选JSON：{day:'yyyy-MM-dd', process:'工序', keyword:'关键字', collectFlag:0|1}", required = false, paramType = "body")
    })
    @SaIgnore
    @PostMapping("/devices")
    public AjaxResult getDeviceList(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day,
            @RequestParam(required = false) String process,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer collectFlag,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestBody(required = false) Map<String, Object> body) {
        if (body != null) {
            if (day == null && body.get("day") instanceof String) {
                day = LocalDate.parse((String) body.get("day"));
            }
            if ((process == null || process.isEmpty()) && body.get("process") instanceof String) {
                process = (String) body.get("process");
            }
            if ((keyword == null || keyword.isEmpty()) && body.get("keyword") instanceof String) {
                keyword = (String) body.get("keyword");
            }
            if (collectFlag == null) {
                Object cf = body.get("collectFlag");
                if (cf instanceof Number) {
                    collectFlag = ((Number) cf).intValue();
                } else if (cf instanceof String && !((String) cf).isEmpty()) {
                    try { collectFlag = Integer.parseInt((String) cf); } catch (Exception ignored) {}
                }
            }
            if (pageNum == null) {
                Object pn = body.get("pageNum");
                if (pn instanceof Number) pageNum = ((Number) pn).intValue();
                else if (pn instanceof String && !((String) pn).isEmpty()) {
                    try { pageNum = Integer.parseInt((String) pn); } catch (Exception ignored) {}
                }
            }
            if (pageSize == null) {
                Object ps = body.get("pageSize");
                if (ps instanceof Number) pageSize = ((Number) ps).intValue();
                else if (ps instanceof String && !((String) ps).isEmpty()) {
                    try { pageSize = Integer.parseInt((String) ps); } catch (Exception ignored) {}
                }
            }
        }
        PageHelper.startPage(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        // 查询数据
        List<Map<String, Object>> list = dashboardService.getDeviceList(day, process, keyword, collectFlag);
        // 返回分页结果
        return Page.getDataTable(list);
    }

    	/**
	 * 获取默认设备状态统计（全部设备）
	 * @return 状态统计
	 */
	@ApiOperation("获取默认设备状态统计（支持工序筛选）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "process", value = "工序筛选", required = false, paramType = "query")
    })
	@SaIgnore
	@GetMapping("/status/stats/default")
	public AjaxResult getDefaultDeviceStatusStats(@RequestParam(required = false) String process) {
        // 复用带工序的统计
        java.util.List<java.util.Map<String,Object>> items = dashboardService.getDeviceStatusStats(process);
        long total = 0L;
        if (items != null) {
            for (java.util.Map<String,Object> row : items) {
                Object c = row.get("count");
                if (c instanceof Number) total += ((Number)c).longValue();
            }
        }
        if (items != null) {
            for (java.util.Map<String,Object> row : items) {
                row.remove("total");
            }
        }
        java.util.Map<String,Object> payload = new java.util.HashMap<>();
        payload.put("total", total);
        payload.put("items", items);
		return AjaxResult.success(payload);
	}
	
	/**
	 * 获取设备状态统计
	 * @param process 工序筛选
	 * @return 状态统计
	 */

	//TODO目前无法区分采集状态
	@ApiOperation("获取设备状态统计")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "process", value = "工序筛选", required = false, paramType = "query")
	})
	@GetMapping("/status/stats")
	public AjaxResult getDeviceStatusStats(
			@RequestParam(required = false) String process) {
		return AjaxResult.success(dashboardService.getDeviceStatusStats(process));
	}


}